<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/23
 * Time: 14:21
 */

namespace app\api\service;

use app\api\exception\BaseException;
use app\api\model\Recommend as RecommendModel;
use app\api\model\User as UserModel;
use think\Db;


class User
{
    /**
     * 判断金币是否充足
     * @param $user_id
     * @param $need_gold
     * @return int
     * @throws \think\exception\DbException
     */
    public static function checkGoldBalance($user_id, $need_gold)
    {
        //判断金币是否充足,扣除金币
        $user = UserModel::get($user_id);
        if ($user['gold'] - $user['frozen_gold'] < $need_gold) {
            return 0;
        }
        return 1;
    }

    /**
     * 充值分红
     * @param $user_id
     * @param $amount
     * @param $type_str
     * @throws \think\exception\DbException
     */
    public static function rechargeReward($user_id, $amount, $type_str)
    {
        $ratio = config('config.充值奖励_比例');
        $reward_amount = $amount * $ratio;
        $user = UserModel::get($user_id);
        $parentid = $user['parentid'];
        if ($parentid) {
            $p_user = UserModel::get($parentid);
            if ($p_user['level'] == 0) {
                $p_user->frozen_money = $p_user['frozen_money'] + $reward_amount;
                $title = '直推会员' . $user['nickname'] . '(ID:' . $user['id'] . ')' . $type_str . '奖励(冻结)';
            } else {
                $title = '直推会员' . $user['nickname'] . '(ID:' . $user['id'] . ')' . $type_str . '奖励';
                $p_user->money = $p_user['money'] + $reward_amount;
            }
            $log_data[] = [
                'title' => $title,
                'user_id' => $parentid,
                'task_id' => '',
                'type' => 1,
                'amount' => $reward_amount,
                'add_time' => time(),
            ];
            $p_user->total_money = $p_user['total_money'] + $reward_amount;
            $p_user->save();
            //奖励推送
            $p_push_info = [
                'alert' => $title . $reward_amount,
            ];
            Push::income($parentid, $p_push_info);
        }
        $promoter = (new User())->getPromoter($user);
        $promoter_id = $promoter['id'];
        if ($promoter_id) {
            $pro_user = UserModel::get($promoter_id);
            if ($pro_user['level'] == 0) {
                $title = '团队会员' . $user['nickname'] . '(ID:' . $user['id'] . ')' . $type_str . '奖励(冻结)';
                $pro_user->frozen_money = $pro_user['frozen_money'] + $reward_amount;
            } else {
                $title = '团队会员' . $user['nickname'] . '(ID:' . $user['id'] . ')' . $type_str . '奖励';
                $pro_user->money = $pro_user['money'] + $reward_amount;
            }
            $log_data[] = [
                'title' => $title,
                'user_id' => $promoter_id,
                'task_id' => '',
                'type' => 1,
                'amount' => $reward_amount,
                'add_time' => time(),
            ];
            $pro_user->total_money = $pro_user['total_money'] + $reward_amount;
            $pro_user->save();
            //奖励推送
            $pro_push_info = [
                'alert' => $title . $reward_amount,
            ];
            Push::income($promoter_id, $pro_push_info);
        }
        if (!empty($log_data)) {
            Db::name('money')->insertAll($log_data);
        }
    }

    /**
     * 升级会员,冻结金额转余额
     * @param $user_id
     * @throws \think\exception\DbException
     */
    public static function frozenToMoney($user_id)
    {
        $user = UserModel::get($user_id);
        if ($user['frozen_money'] != 0) {
            $user->money = $user['money'] + $user['frozen_money'];
            $user->total_money = $user['total_money'] + $user['frozen_money'];
            $user->frozen_money = 0;
            $user->save();
            //记录日志
            $data = [
                'title' => $user['nickname'] . '(ID:' . $user_id . ')升级,冻结金额转余额',
                'user_id' => $user_id,
                'task_id' => '',
                'type' => 1,
                'amount' => $user['frozen_money'],
                'add_time' => time(),
            ];
            Db::name('money')->insertAll($data);
        }
    }

    /**
     * token获取user_id
     * @return mixed
     * @throws BaseException
     */
    public static function getUserIdByToken()
    {
        $token = input('get.token');
//        $user_id = Db::name('user_login')->where('token', $token)->where('expiretime', '>', time())->value('user_id');
        $user_id = UserModel::where(['token' => $token])->value('id');
        if (!$user_id) {
            throw new BaseException(['errorCode' => 101, 'msg' => '请重新登录']);
        }
        return $user_id;
    }

    /**
     * 生成Token值
     * @return string
     */
    public static function generateToken()
    {
        //32个字符组成一组随机字符串
        $randChars = get_rand_char(32);
        //
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        //salt 盐
        $salt = config('config.token_salt');

        //用三组字符串，进行md5加密
        return md5($randChars . $timestamp . $salt);
    }

    /**
     * 上传在线图片 -- 微信头像
     * @param $headimg_url
     * @param $openid
     * @return string
     * 没有使用
     */
    public static function uploadWechatHeadimg($headimg_url, $openid)
    {

        $headimg = file_get_contents($headimg_url);
        $dir = DS . 'uploads' . DS . 'wechat' . DS . md5($openid) . DS;
        $mkdir = ROOT_PATH . 'public' . $dir;
        if (!is_dir($mkdir)) {
            mkdir($mkdir);
        }
        $filename = md5($openid) . '.jpg';
        $save = $mkdir . $filename;
        $res = file_put_contents($save, $headimg);
        return $dir . $filename;
    }

    /**
     * 验证用户每日领取任务次数--发圈和接任务同一次数
     * @param array $user =  ['level'=>'','task_time=>'']
     * @return bool
     */
    public static function checkDailyTaskTime($user)
    {
        if ($user['level'] == 0 && $user['task_time'] >= 3) {
            return false;
        }
        if ($user['level'] == 1 && $user['task_time'] >= 10) {
            return false;
        }
        if ($user['level'] == 2 && $user['task_time'] >= 20) {
            return false;
        }
        return true;
    }

    //生成推广码
    public static function generateRequestCode(){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $max = strlen($strPol) - 1;

        for ($i = 0;
             $i < 2;
             $i++) {
            $str .= $strPol[rand(0, $max)];
        }

        $random = substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $code = $str.$random;
        $res = UserModel::where('request_code',$code)->field('id')->find();
        if ($res){
            $code = self::generateRequestCode();
        }
        return $code ;
    }


    //获取脉大师
    /*public static function getPromoter1($user_id){
        $user = UserModel::get($user_id);
        $p_id = $user['parentid'];
        $p_user = UserModel::get($p_id);
        if ($p_user['is_promoter'] == 0){
            self::getPromoter($p_user['parentid']);
        }
        return $p_user;
    }*/

    //获取脉大师
    /*public static function getPromoter2($user){
        if ($user['id'] == 1){
            return false;
        }else{
            $p_id = $user['parentid'];
            $p_user = UserModel::get($p_id);
            if ($p_user['is_promoter'] == 0){
                $p_user = self::getPromoter2($p_user);
            }
                return $p_user;
        }
    }*/

    //获取脉大师
    public static function getPromoter($user){
        $route = $user['route'];
        $route =trim($route,',');
        $promoter =(new UserModel())->whereIn('id',$route)->where('depth', '<',$user['depth'])->where('is_promoter','=',1)->field('id')->order('depth desc')->find();
        return $promoter;
    }

    //增加团队人数
    public static function incTeam($user){
        $route = $user['route'];
        $route =trim($route,',');
        UserModel::whereIn('id',$route)->setInc('team');
    }

    //计算会员到期时间
    public static function getMemberTime($user){
        $u_add_time = strtotime(date('Y-m-d',$user['add_time']));
        $month = (date('y') - date('y',$u_add_time)) * 12 + (date('m') - date('m',$u_add_time));
        $time1 = date('Ymd',strtotime('+'.$month. ' month',$u_add_time)); //
        $time2 = date('Ymd');
        if ($time2 >= $time1){
            $month ++;
        }
        $member_time = strtotime('+'.$month. ' month',$u_add_time);
        return $member_time;
    }

    //判断是否有发圈资格
    public static function isMember($member_time){
        if ($member_time < time()){
            return false;
        }else{
            return true;
        }
    }



}